<?php
namespace app\appadmin\controller\v1;
use app\app\Appbase;

//
//用户
//
class User extends Appbase 
{
	
	//是否返回
    private  $isGetCount = false;
	
	/**
    * 构造函数自动执行
    * @return null
    */
    public function __construct($isGetCount=false){
    	$this ->isGetCount =  $isGetCount;
    }
	
		
	/**
     * 获取示例
     * @param array $options 实例配置
     * @return static
     */
    public  function instance($isRe=false)
    {
        return new self($isRe);
    }
	
	
	/**
	* 获取用户列表
	* /appadmin/v1/user/getUserList
	* 是否需要登录 
	* @is_need_login true
	*/
	public function getUserList($name=''){
		$shopId = request()->shopId;
		try {
	        $model = model("user_vip");
	        $model = $model->alias('a');
	        $model = $model->leftJoin('user b','a.uid=b.id');
	        $model = $model->field("a.uid,a.phone,a.name,a.sex,a.birthday,a.code");
	        $model = $model->field("b.balance,b.integral");
	        $model = $model->where(function($query) use($name) {
	        	$query->where('a.name','like',"%$name%");
	        	$query->whereor('a.phone','like',"%$name%");
	        });
	        $model = $model->page(input('pageIndex') ?: 1,input('pageSize') ?: 20);
	        $model = $model->where('b.shop_id',$shopId);
			return $this->ReSucess( $model->select() );	
		} catch (\Exception $e) {
			return $this->ReError($e->getMessage());	
		}
	}
	
	
	/**
	* 获取用户信息
	* /appadmin/v1/user/getUserInfo
	* 是否需要登录 
	* @is_need_login true
	*/
	public function getUserInfo($uid){
		try {
			//TODO 用户信息
	        $table = model('ShopYyOrder')->order('id desc')->where('status',1)->limit(99999)->buildSql();
	        $model = model("user")->alias('b');
	        $model = $model->leftJoin('user_vip a','a.uid=b.id');
	      	$model = $model->leftJoin("$table c",'c.uid = a.uid');
	      	$model = $model->leftJoin("
	        	( 
	        		select uid,shop_id, sum(pay_price)  consume from xw_order 
	        		where is_pay = 1 and pay_type <> 'brokerage'
	        		group by uid,shop_id
	        	)  d
	        ",'b.id = d.uid and b.shop_id = d.shop_id');
	        $model = $model->leftJoin("
	        	( 
	        		select uid,shop_id,count(id) nums from xw_shop_yy_order  
	        		where status = 1 
	        		group by uid, shop_id
	        	)  e
	        ",'b.id = e.uid and b.shop_id = e.shop_id');
	        $model = $model->leftJoin("
	        	( 
	        		select uid,shop_id,count(id) nums from xw_user_hf_log  
	        		group by uid,shop_id
	        	)  g
	        ",'b.id = g.uid and b.shop_id = g.shop_id ');
	        $model = $model->leftJoin("
	        	( 
	        		select uid,shop_id,count(*) nums from xw_shop_qzproj
	        		group by uid,shop_id
	        	)  h
	        ",'b.id = h.uid and b.shop_id =h.shop_id ');
	        $model = $model->field("b.id as uid,a.phone,a.sex,a.birthday,b.balance");
	        $model = $model->field("ifnull(a.name,b.nickname) name");
	        $model = $model->field("datediff(ifnull(c.add_time,b.add_time),now()) as day");
	        $model = $model->field("ifnull(e.nums,0) as shop_num");
	        $model = $model->field("ifnull(d.consume,0) consume");
	        $model = $model->field("ifnull(g.nums,0) as  hf_num");
	        $model = $model->field("ifnull(h.nums,0) as  qz_proj");
	        $model = $model->where('b.id',$uid);
	        $res = $model->find();
	        
	        $res['order_num'] = (new self(true))->consumeBill($uid);
	        $res['dhl_proj'] = (new self(true))->dhlProj(-1,-1,$uid);
	        $res['kdq_num'] = (new self(true))->tcdq(-1,-1,$uid);
	        
			return $this->ReSucess( $res );	
		} catch (\Exception $e) {
			return $this->ReError($e->getMessage());	
		}
	}
	
	/**
	* 更新密码
	* /appadmin/v1/user/updatepwd
	* 是否需要登录 
	* @is_need_login true
	*/
	public function updatepwd($pwd,$newPwd){
		if(request()->identity !== 3){
      		return $this->ReError( '店员身份才有权限操作！' );
    	}
    	if( empty($newPwd)  ){
    		return $this->ReError( '新密码不能未空！' );
    	}
		$userId = request()->userId;
		if(!$staff = model('shop_staff')->where('password',md5($pwd))->get($userId)){
			return $this->ReError( '原密码不正确！' );
		}
		$staff->password = md5($newPwd);
		$staff->save();
		return $this->ReSucess($data);	
	}
	
	/**
	* 消费记录
	* /appadmin/v1/user/consumeBill
	* 是否需要登录 
	* @is_need_login true
	*/
	public function consumeBill($uid,$type='1'){
		$shopId = request()->shopId;
		try {  
			$model = model('order')
				->with(['goodsList','shopInfo'])
				->where('is_pay',1)
				->where('uid',$uid)
				->where('shop_id',$shopId)
				->field('id,shop_id,order_no,total_old_price,total_sale_price,total_sale_old_price')
				->field('discount_price,total_price,pay_price,freight_price,deduct_price,coupon_price')
				->field("if(pay_type = 'balance','余额','微信支付') as pay_type,pay_time");
			
			if($this ->isGetCount)  return $model->count();
	    	
	    	$model = $model->order('add_time','desc');
	    	$model = $model->page(input('pageIndex') ?: 1,input('pageSize') ?: 20);
	    	
			$list = $model->select();
			
			return $this->ReSucess($list);	
		} catch (\Exception $e) {
			return $this->ReError($e->getMessage());	
		}
	}
	
	/**
	* 待护理项目
	* /appadmin/v1/user/dhlProj
	* 是否需要登录 
	* @is_need_login true
	*/
	public function dhlProj($shop_id='',$staff_id=-1,$uid=''){
		$shopId = !$shop_id ? request()->shopId : $shop_id;
		
		$wxUid = request()->wxUid;
		try {
			
	        $table  = model('ShopYyOrder')->order('id desc')->where('status',1)->limit(99999)->buildSql();
			$model = model('user_yg_proj')->alias('a')
				->leftJoin('goods b','b.id = a.goods_id')
				->leftJoin('goods_specs d','d.id = a.specs_id')
	        	->leftJoin("$table e",'e.uid = a.uid')
	        	->leftJoin('user_vip c','c.uid = a.uid')
	        	->leftJoin('user u','u.id = a.uid')
	        	->field("c.uid,c.name as user_name,c.phone")
	    		->field("c.id as proj_id")
	    		->field("concat(b.name,' / ',d.name) as proj_name")
	    		->field("datediff(ifnull(e.add_time,u.add_time),now()) as day")
	    		->where('a.use_num < a.num')
	    		->whereNotNull('u.id')
	    		->order('a.add_time','desc')
	    		->group('a.shop_id,a.uid,a.specs_id');
	    
	    	if($shopId !=-1) $model = $model->where('a.shop_id',$shopId);
	    	
	    	if( $uid!=-1 && $uid!='' ){
	    		$model = $model->where('a.uid',$uid);	
	    	}else if($wxUid && $staff_id!=-1) {
	    		$model = $model->where('u.spread_uid',$wxUid);	
	    	}
	    	
	    	if($this ->isGetCount) return $model->count();
	    	
	    	$model = $model->page(input('pageIndex') ?: 1,input('pageSize') ?: 20);
        		
        	$data =[];
        	foreach( $model->select() as $key => $value ){
    			$value['count']  = model('ShopYyOrder')->where('status',1)
    				->where('uid',$value['uid'])
    				->count();
    			$value['consume'] = model('user')->consume($value['uid'],$shopId);
    			$data[] = $value;
        	}	
        	
        
			//返回
			return $this->ReSucess($data);	
			
		} catch (\Exception $e) {
			return $this->ReError($e->getMessage());	
		}
	}
	
	
	/**
	* 套餐到期
	* /appadmin/v1/user/tcdq
	* $shop_id  店铺id, -1所有店铺的所有统计,不传或空默认取当前登录的身份信息过滤
	* $staff_id  员工id, -1所有员工的所有统计,不传或空默认取当前登录的身份信息过滤
	* 是否需要登录 
	* @is_need_login true
	*/
	public function tcdq($shop_id='',$staff_id='',$uid=''){
		$shopId = !$shop_id ? request()->shopId : $shop_id;
		$wxUid = request()->wxUid;
		try {
			$isRemind =  getSystem("buess_shop_tcdq_remind",$shopId) ?? 3;
			$table = model('user_yg_proj')->order('id desc')->where('status',1)->limit(1)->buildSql();
	        $model = model('user_yg_meal')->alias('a')
	        	->leftJoin('goods b','b.id = a.goods_id')
				->leftJoin('goods_specs d','d.id = a.specs_id')
	        	->leftJoin('user_vip c','c.uid = a.uid')
	        	->leftJoin('user u','u.id = a.uid')
	        	->leftJoin("$table e",'e.uid =a.uid')
	        	->field("c.uid,ifnull(c.name,u.nickname) as user_name,c.phone")
	    		->field("u.id as proj_id")
	    		->field("concat(b.name,' / ',d.name) as proj_name")
	    		->field("a.id,datediff(ifnull(e.add_time,u.add_time),now()) as day")
	        	->field('DATE_ADD(a.add_time, interval a.effective_time MONTH) effective_time')
	        	->whereNotNull('u.id')
	        	->whereExp("$isRemind",">= datediff(DATE_ADD(a.add_time, interval a.effective_time MONTH),now())");
	        
	        if($shopId!=-1) $model = $model->where('u.shop_id',$shopId);	
	        
	        if( $uid!=-1 && $uid!='' ){
	    		$model = $model->where('a.uid',$uid);	
	    	}else if($wxUid && $staff_id!=-1) {
	    		$model = $model->where('u.spread_uid',$wxUid);	
	    	}
	    	
	    	if($this ->isGetCount) return $model->count();
	    	
	    	$model = $model->order('a.add_time','desc');
	    	$model = $model->page(input('pageIndex') ?: 1,input('pageSize') ?: 20);
        		
        	$data =[];
        	foreach( $model->select() as $key => $value ){
    			$value['count'] = model('ShopYyOrder')->where('status',1)->where('uid',$value['uid'])->count();
    			$value['consume'] = model('user')->consume($value['uid'],$shopId);
    			$data[] = $value;
        	}
	    	
			//返回
			return $this->ReSucess($data);	
			
		} catch (\Exception $e) {
			return $this->ReError($e->getMessage());	
		}
	}
	
	
	/**
	* 提醒 - 余额不足 - 
	* /appadmin/v1/user/yebz
	* $shop_id  店铺id, -1所有店铺的所有统计,不传或空默认取当前登录的身份信息过滤
	* $staff_id  员工id, -1所有员工的所有统计,不传或空默认取当前登录的身份信息过滤
	* 需要登录 
	* @is_need_login true
	*/
	public function yebz($shop_id='',$staff_id='',$uid=''){
		$shopId = !$shop_id ? request()->shopId : $shop_id;
		$wxUid = request()->wxUid;
		try {
			
			$remind = getSystem("buess_shop_balance_remind", $shopId) ?: 0;
			$table = model('user_yg_proj')->order('id desc')->where('status',1)->limit(1)->buildSql();
	        $model = model('user')->alias('a')
	        	->leftJoin('user_vip c','c.uid = a.id')
	        	->leftJoin("$table e","e.uid =a.id")
	        	->field("a.id as uid,c.name as user_name,c.phone,a.id as proj_id")
	    		->field("a.balance,datediff(ifnull(e.add_time,a.add_time),now()) as day")
	    		->whereNotNull("c.id")
	    		->where("balance","<=",$remind);
	    			
	        if($shopId!=-1) $model = $model->where('a.shop_id',$shopId);	
	        
	    	if( $uid!=-1 && $uid!='' ){
	    		$model = $model->where('a.uid',$uid);	
	    	}else if($wxUid && $staff_id!=-1) {
	    		$model = $model->where('a.spread_uid',$wxUid);	
	    	}
	    	
	    	if($this ->isGetCount) return $model->count();
	    	
	    	$model = $model->page(input('pageIndex') ?: 1,input('pageSize') ?: 20);
        		
        	$data =[];
        	foreach( $model->select() as $key => $value ){
    			$value['count'] = model('ShopYyOrder')->where('status',1)
    				->where('uid',$value['uid'])
    				->count();
    			$value['consume'] = model('user')->consume($value['uid'],$shopId);
    			$data[] = $value;
        	}
	    	
			//返回
			return $this->ReSucess($data);	
			
		} catch (\Exception $e) {
			return $this->ReError($e->getMessage());	
		}
	}
	
	
	/**
	* 提醒 - 保养项目
	* /appadmin/v1/user/byProject
	* $shop_id  店铺id, -1所有店铺的所有统计,不传或空默认取当前登录的身份信息过滤
	* $staff_id  员工id, -1所有员工的所有统计,不传或空默认取当前登录的身份信息过滤
	* 需要登录 
	* @is_need_login true
	*/
	public function byProject($shop_id='',$staff_id='',$uid=''){
		$shopId = !$shop_id ? request()->shopId : $shop_id;
		$wxUid = request()->wxUid;
		try {
			
	        $remind =  getSystem("buess_shop_proj_remind",$shopId) ?: 0;
	        $model = model('ShopYyOrder');
	        $table  = $model->order('id desc')->where('status',1)->limit(99999)->buildSql();
			$model = $model->table( $table .'as a' )
				->leftJoin('user_yg_proj d','d.id = a.proj_id')
				->leftJoin('goods b','b.id = d.goods_id')
	        	->leftJoin('user_vip c','c.uid = a.uid')
	        	->leftJoin('user u','u.id = a.uid')
	        	->field("a.uid,c.name as user_name,c.phone")
	    		->field("b.id as proj_id")
	    		->field("b.name as proj_name")
	    		->field("datediff(a.add_time,now()) as day")
	    		->whereNotNull('c.uid');
	    	
	    	if($uid!=-1 && $uid!='' ){
	    		$model = $model->group('a.uid');
	    	}	
	    	
        	if($shopId!=-1) $model = $model->where('a.shop_id',$shopId);	
	    	if( $uid!=-1 && $uid!='' ){
	    		$model = $model->where('a.uid',$uid);	
	    	}else if($wxUid && $staff_id!=-1) {
	    		$model = $model->where('u.spread_uid',$wxUid);	
	    	}
	    	
	    	if($this ->isGetCount) return $model->count();
	    	
	    	$model = $model->page(input('pageIndex') ?: 1,input('pageSize') ?: 20);
   			
        	$data =[];
        	foreach( $model->select() as $key => $value ){
        		if( (-$value['day']) >= $remind ){
        			$value['count']  = model('ShopYyOrder')
        				->where('status',1)
        				->where('uid',$value['uid'])
        				->count();
        			$value['consume'] = model('user')->consume($value['uid'],$shopId);	
        			$data[] = $value;
        		}
        	}	
        	
			//返回
			return $this->ReSucess($data);	
			
		} catch (\Exception $e) {
			return $this->ReError($e->getMessage());	
		}
	}
	
	
	/**
	* 提醒 - 生日
	* /appadmin/v1/user/birthday
	* $shop_id  店铺id, -1所有店铺的所有统计,不传或空默认取当前登录的身份信息过滤
	* $staff_id  员工id, -1所有员工的所有统计,不传或空默认取当前登录的身份信息过滤
	* 需要登录 
	* @is_need_login true
	*/
	public function birthday($shop_id='',$staff_id='',$uid=''){
		$shopId = !$shop_id ? request()->shopId : $shop_id;
		$wxUid = request()->wxUid;
		try {
	        $remind =  getSystem("buess_shop_birthday_remind",$shop_id) ?: 7;
	        $start = date('m-d');
        	$end = date('m-d', strtotime("$remind day"));
	        $table  = model('ShopYyOrder')->order('id desc')->where('status',1)->limit(99999)->buildSql();
			$model = model('user_vip')->alias('a' )
	        	->leftJoin("$table c",'c.uid = a.uid')
	        	->leftJoin('user u','u.id = a.uid')
	        	->field("a.uid,a.name as user_name,a.phone,a.birthday")
	    		->field("datediff(ifnull(c.add_time,u.add_time) ,now()) as day")
	    		->where([['','exp',\Db::raw("substr(a.birthday,6,7) between '$start' and '$end'")]])
	    		->group('a.uid');

        	if( $shopId!=-1 ) $model = $model->where('u.shop_id',$shopId);	
        	
	    	if( $uid!=-1 && $uid!='' ){
	    		$model = $model->where('u.uid',$uid);	
	    	}else if($wxUid && $staff_id!=-1) {
	    		$model = $model->where('u.spread_uid',$wxUid);	
	    	}
	    	
	    	if($this ->isGetCount) return $model->count();
	    	
	    	$model = $model->page(input('pageIndex') ?: 1,input('pageSize') ?: 20);
   
        	$data =[];
        	foreach( $model->select() as $key => $value ){
    			$value['count']  = model('ShopYyOrder')->where('status',1)->where('uid',$value['uid'])->count();
    			$value['consume'] = model('user')->consume($value['uid'],$shopId);	
    			$data[] = $value;
        	}	
        	
        	
			//返回
			return $this->ReSucess($data);	
			
		} catch (\Exception $e) {
			return $this->ReError($e->getMessage());	
		}
	}
	
	
	/**
	* 负责客户数
	* /appadmin/v1/user/fzkh
	* $shop_id  店铺id, -1所有店铺的所有统计,不传或空默认取当前登录的身份信息过滤
	* $staff_id  员工id, -1所有员工的所有统计,不传或空默认取当前登录的身份信息过滤
	* 需要登录 
	* @is_need_login true
	*/
	public function fzkh($shop_id='',$staff_id='',$type=1){
		$shopId = !$shop_id ? request()->shopId : $shop_id;
		$wxUid = request()->wxUid;
		try {
			
	        $table  = model('ShopYyOrder')->order('id desc')->where('status',1)->limit(10000000)->buildSql();
			$model = model('user')->alias('u')
				->leftJoin('user_vip a','u.id = a.uid')
	        	->leftJoin("$table c",'c.uid = u.id and c.shop_id=u.shop_id')
	        	->leftJoin('user_yg_proj y','y.id = c.proj_id')
	        	->leftJoin('goods b','b.id = y.goods_id')
				->leftJoin('goods_specs d','d.id = y.specs_id')
				->field("u.id as uid,ifnull(a.name,u.nickname) as user_name,a.phone,a.birthday")
	    		->field("c.proj_id as proj_id")
	    		->field("concat(b.name,' / ',d.name) as proj_name")
	    		->field("datediff(ifnull(c.add_time,u.add_time) ,now()) as day")
	    		->group('u.id');
        	
        	if($type==2){
        		$isRemind =  getSystem("buess_shop_khls_remind",$shopId) ?? 30;
        		$model = $model->whereExp("-$isRemind",">= ifnull(datediff(c.add_time,now()),datediff(u.add_time,now()))");
        	}
        	
        	if( $shopId !=-1 ) $model = $model->where('u.shop_id',$shopId);	
        	
	    	if($staff_id!=-1) { $model = $model->where('u.spread_uid',$wxUid);	 }
	    	
	    	if($this ->isGetCount) return $model->count();
	    	
	    	$model = $model->page(input('pageIndex') ?: 1,input('pageSize') ?: 20);
   
        	$data =[];
        	foreach( $model->select() as $key => $value ){
    			$value['count']  = model('ShopYyOrder')->where('status',1)->where('uid',$value['uid'])->count();
    			$value['consume'] = model('user')->consume($value['uid'],$shopId);	
    			$data[] = $value;
        	}	
        	
			//返回
			return $this->ReSucess($data);	
			
		} catch (\Exception $e) {
			return $this->ReError($e->getMessage());	
		}
	}
	
	
}



